<script setup lang="ts">
import { ref } from 'vue'
import { addProductUsingPost } from '@/api/productController.ts'
import { message } from 'ant-design-vue'
import ImageUpload from '@/components/ImageUpload.vue'
import { STATUS_TYPE_OPTIONS } from '@/constants/product.ts'

interface Props {
  isOpen?: boolean
  closeModal?: () => void
  refreshData?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  isOpen: false,
  closeModal: () => {},
  refreshData: () => {},
})

const product = ref<API.ProductAddDto>({})

// 回调函数
const onSuccess = (newImage: string) => {
  product.value.image = newImage
}

// 新增商品
const addProduct = async () => {
  const res = await addProductUsingPost({
    ...product.value,
  })
  if (res.code === 200 && res.data) {
    message.success('新增成功')
    props.closeModal?.()
    props.refreshData?.()
    product.value = {}
  } else {
    message.error(res.message)
  }
}
</script>

<template>
  <div id="product-add-view">
    <a-modal
      v-model:open="props.isOpen"
      title="新增商品信息"
      ok-text="提交"
      cancel-text="取消"
      @cancel="props.closeModal()"
      @ok="addProduct"
    >
      <a-form :model="product">
        <a-form-item label="图片">
          <image-upload :product="product" :on-success="onSuccess" />
        </a-form-item>
        <a-form-item label="名称">
          <a-input v-model:value="product.name" />
        </a-form-item>
        <a-form-item label="描述">
          <a-input v-model:value="product.description" />
        </a-form-item>
        <a-form-item label="价格">
          <a-input v-model:value="product.price" />
        </a-form-item>
        <a-form-item label="库存">
          <a-input v-model:value="product.stock" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="product.status"
            :options="STATUS_TYPE_OPTIONS"
            placeholder="请选择状态"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped></style>
